const express = require('express')
const router = express.Router()
const Comment = require('../../model/Comment')

//添加评论
router.post('/add', (req, res) => {
  new Comment(req.body).save().then(comment => res.json(comment))
})

//全部评论
router.get('/', (req, res) => {
  Comment.find().then(comment => res.json(comment))
})

//新闻id查询评论
router.get('/newsId/:id', (req, res) => {
  Comment.find({
    nid: req.params.id
  }).then(comment => res.json(comment))
})

//用户名查询评论
router.get('/username/:username', (req, res) => {
  Comment.find({
    username: req.params.username
  }).then(comment => res.json(comment))
})

//关键词查询
router.post('/search', (req, res) => {
  Comment.find({content: {$regex: req.body.keyword, $options: 'i'}})
    .then(comment => {
      if (!comment) return res.status(404).json('没有任何内容')
      res.json(comment)
    })
    .catch(err => res.status(404).json(err))
})

//删除单条评论
router.delete('/delete/:id', (req, res) => {
  Comment.findOneAndRemove({
    _id: req.params.id
  }).then(comment => res.json(comment))
    .catch(err => res.status(404).json('删除失败'))
})


module.exports = router